﻿#pragma once
//此类主要 处理服务器推送过来的消息

//#include "pthread.h"
#include "cocos2d.h"
#include "Message.h"
#include "ByteBuf.h"
#include <vector>
#include <list>
#include <thread>
#include <functional>

/*
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};*/
using namespace cocos2d;
using namespace std;


typedef void (cocos2d::Ref::*ResPonseThreadEvent)(short,Message*);
#define callFunc_selectormsg(_SELECTOR) (ResPonseThreadEvent)(&_SELECTOR)

#define M_ADDCALLBACKEVENT(varName)\
protected: cocos2d::Ref* m_##varName##listener;ResPonseThreadEvent varName##selector;\
public: void add##varName##ListenerEvent(ResPonseThreadEvent m_event,cocos2d::Ref* listener)  { m_##varName##listener=listener;varName##selector=m_event; }
// 64m is enough
#define BUFF_SIZE 67108864
class ResPonseThread:public cocos2d::Node
{
public:	
	~ResPonseThread(void);
	static ResPonseThread*   getInstance(); //获取该类的单利

	int start (void * =NULL); //函数是线程启动函数，其输入参数是无类型指针。
	void stop();    //函数中止当前线程。
	void sleep (int tesec); //函数让当前线程休眠给定时间，单位为毫秒秒。
	void detach();   
	void * wait();

    void schedule_func(float ti);
	void msgCallBack(short commttpe, Message* msg);
	void notContCallBack(short commttpe, Message* msg);
	function<void()> onReconned;
private:
    /*pthread_mutex_t*/mutex _messageQueueMutex;
    list<Message*> messages;
    __NotificationCenter *notfication;
	ResPonseThread(void);
	/*pthread_t*/thread handle; 
	bool started;
	bool detached;
	int num;//重新连接次数 
	
	ByteBuf recv_buf;
	static void* buf;
	static void * threadFunc(void *);
	static ResPonseThread* m_pInstance;	
	M_ADDCALLBACKEVENT(msg);///聊天回调函数

	M_ADDCALLBACKEVENT(notcon);//错误的回调
	static string bytestohexstring(char* bytes, int bytelength);	
};
